package com.sincon.system.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.hutool.json.JSONObject;
import com.sincon.common.utils.SecurityUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sincon.system.mapper.TbVideoInfoMapper;
import com.sincon.system.domain.TbVideoInfo;
import com.sincon.system.service.ITbVideoInfoService;
import org.springframework.util.CollectionUtils;

/**
 * 视频任务三连配置Service业务层处理
 * 
 * @author LaoGao
 * @date 2024-12-23
 */
@Service
public class TbVideoInfoServiceImpl implements ITbVideoInfoService 
{
    private static final String QR_CODE_URL = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate";
    private static final String QR_CODE_CHECK_URL = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll";
    private final CloseableHttpClient httpClient;
    private final RequestConfig requestConfig;
    public TbVideoInfoServiceImpl() {
        this.requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(5000)
                .build();

        this.httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
    }
    @Autowired
    private TbVideoInfoMapper tbVideoInfoMapper;




    /**
     * 查询视频任务三连配置
     * 
     * @param id 视频任务三连配置主键
     * @return 视频任务三连配置
     */
    @Override
    public TbVideoInfo selectTbVideoInfoById(Long id)
    {
        return tbVideoInfoMapper.selectTbVideoInfoById(id);
    }

    /**
     * 查询视频任务三连配置列表
     * 
     * @param tbVideoInfo 视频任务三连配置
     * @return 视频任务三连配置
     */
    @Override
    public List<TbVideoInfo> selectTbVideoInfoList(TbVideoInfo tbVideoInfo) throws IOException {
        List<TbVideoInfo> tbVideoInfos = tbVideoInfoMapper.selectTbVideoInfoList(tbVideoInfo);
        if(!CollectionUtils.isEmpty(tbVideoInfos)) {
            for (TbVideoInfo videoInfo : tbVideoInfos) {
                String apiUrl = "https://api.bilibili.com/x/web-interface/view?bvid=" + videoInfo.getVideoBv();
                HttpGet httpGet = new HttpGet(apiUrl);
                HttpResponse response = httpClient.execute(httpGet);
                String jsonResponseString = EntityUtils.toString(response.getEntity());
                JSONObject jsonResponse = new JSONObject(jsonResponseString);

                // Check if the response contains the expected data
                if (jsonResponse.getInt("code") == 0) {
                    JSONObject data = jsonResponse.getJSONObject("data");
                    if (data.getStr("bvid").equals(videoInfo.getVideoBv())) {
                        int likes = data.getJSONObject("stat").getInt("like");
                        int favorites = data.getJSONObject("stat").getInt("favorite");
                        int coins = data.getJSONObject("stat").getInt("coin");
                        videoInfo.setCurrentLikes(String.valueOf(likes));
                        videoInfo.setCurrentFavorites(String.valueOf(favorites));
                        videoInfo.setCurrentCoins(String.valueOf(coins));
                    } else {
                        System.out.println("No matching BV found for: " + videoInfo.getVideoBv());
                    }
                } else {
                    System.out.println("Error fetching data for BV: " + videoInfo.getVideoBv());

            }
            }
        }



        return tbVideoInfos;
    }

    /**
     * 新增视频任务三连配置
     * 
     * @param tbVideoInfo 视频任务三连配置
     * @return 结果
     */
    @Override
    public int insertTbVideoInfo(TbVideoInfo tbVideoInfo)
    {
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //通过URL获取标题
        String title = getTitle(tbVideoInfo.getVideoUrl());
        tbVideoInfo.setVideoTitle(title);
        tbVideoInfo.setCreateTime(date.format(new Date()));
        tbVideoInfo.setCurrentLikes("0");
        tbVideoInfo.setCurrentCoins("0");
        tbVideoInfo.setCurrentFavorites("0");
        tbVideoInfo.setCreateName(SecurityUtils.getUsername());
        return tbVideoInfoMapper.insertTbVideoInfo(tbVideoInfo);
    }

    /**
     * 获取视频标题
     * @return
     */
    private String getTitle(String url) {
        String title = "";
        try {
            // 获取网页文档
            Document doc = Jsoup.connect(url).get();

            // 通过选择器获取视频标题
            title= doc.title();

            // 输出视频标题
            System.out.println("视频标题: " + title);
        } catch (Exception e) {
            System.out.println("获取视频标题时出错: " + e.getMessage());
        }

        return  title;

    }

    /**
     * 修改视频任务三连配置
     * 
     * @param tbVideoInfo 视频任务三连配置
     * @return 结果
     */
    @Override
    public int updateTbVideoInfo(TbVideoInfo tbVideoInfo)
    {
        tbVideoInfo.setVideoTitle(getTitle(tbVideoInfo.getVideoUrl()));
        return tbVideoInfoMapper.updateTbVideoInfo(tbVideoInfo);
    }

    /**
     * 批量删除视频任务三连配置
     * 
     * @param ids 需要删除的视频任务三连配置主键
     * @return 结果
     */
    @Override
    public int deleteTbVideoInfoByIds(Long[] ids)
    {
        return tbVideoInfoMapper.deleteTbVideoInfoByIds(ids);
    }

    /**
     * 删除视频任务三连配置信息
     * 
     * @param id 视频任务三连配置主键
     * @return 结果
     */
    @Override
    public int deleteTbVideoInfoById(Long id)
    {
        return tbVideoInfoMapper.deleteTbVideoInfoById(id);
    }
}
